/**
 * Created by leo on 16-12-9.
 */

'use strict';

var _ = require('lodash'),
  path = require('path'),
  mongoose = require('mongoose'),
  User = mongoose.model('User'),
  errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller')),
  validator = require('validator');

/**
 * Show the finded User
 */
exports.me = function (req, res) {
  // Sanitize the user - short term solution. Copied from core.server.controller.js
  var safeUserObject = null;
  if (req.user) {
    safeUserObject = {
      displayName: validator.escape(req.user.displayName),
      provider: validator.escape(req.user.provider),
      username: validator.escape(req.user.username),
      shots_id: validator.escape(req.user.shots_id),
      created: req.user.created.toString(),
      roles: req.user.roles,
      profileImageURL: req.user.profileImageURL,
      email: validator.escape(req.user.email),
      lastName: validator.escape(req.user.lastName),
      firstName: validator.escape(req.user.firstName),
      additionalProvidersData: req.user.additionalProvidersData
    };
  }

  res.json(safeUserObject || null);
};

var whitelistedFields = ['firstName', 'lastName', 'email', 'username'];

/**
 * Update an user
 */
exports.update = function (req, res) {
  // Init Variables
  var user = req.user;

  if (user) {
    // Update whitelisted fields only
    user = _.extend(user, _.pick(req.body, whitelistedFields));

    user.updated = Date.now();
    user.displayName = user.firstName + ' ' + user.lastName;

    user.save(function (err) {
      if (err) {
        return res.status(422).send({
          message: errorHandler.getErrorMessage(err)
        });
      } else {
        req.login(user, function (err) {
          if (err) {
            res.status(400).send(err);
          } else {
            res.json(user);
          }
        });
      }
    });
  } else {
    res.status(401).send({
      message: 'User is not signed in'
    });
  }
};

/*
 * Add Member to Story
 */
exports.addUserToStory = function (req, res) {
  if (req.story && req.findedUser) {
    // add member ref to story
    var story = req.story;
    var members = story.members;
    members.push(req.findedUser);
    story.members = members;

    story.save(function (err) {
      if (err) {
        res.status(422).send({
          message: 'add member to story error'
        });
      } else {
        res.json(story);
      }
    });
  } else {
    res.status(404).send();
  }
};

/*
 * remove Member from Story
 */
exports.removeMemberFromStory = function (req, res) {
  if (req.story && req.findedUser) {
    // remove in story
    var story = req.story;
    var members = story.members;
    for (var i = 0; i < members.length; ++i) {
      if (members[i]._id.toString() === req.findedUser._id.toString()) members.splice(i, 1);
    }
    story.members = members;

    story.save(function (err) {
      if (err) {
        res.status(422).send({
          message: 'remove member to story error'
        });
      } else {
        res.json(story);
      }
    });
  } else {
    res.status(404).send();
  }
};

/**
 * User middleware
 */
exports.userByID = function (req, res, next, id) {
  if (!mongoose.Types.ObjectId.isValid(id)) {
    return res.status(400).send({
      message: 'User id is invalid'
    });
  }

  User.findById(id).exec(function (err, user) {
    if (err) {
      return next(err);
    } else if (!user) {
      return res.status(404).send({
        message: 'No user with that identifier has been found'
      });
    }
    req.findedUser = user;
    next();
  });
};
